import tornado.ioloop
import tornado.web
from tornado.websocket import WebSocketHandler
import os


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")


class WebSocketServer(WebSocketHandler):
    def check_origin(self,origin):
        return True

    def open(self):
        print("WebSocket opened")

    def on_message(self, message):
        print(message)
        self.write_message(u"server said: " + message)

    def on_close(self):
        # 前端如果关闭了websocket的页面，后端这里会自动调用
        print("WebSocket closed")


def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/websocket", WebSocketServer)
    ],
        static_path=os.path.join(os.path.dirname(__file__), "static")
    )


if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
